import { Component, Input, ChangeDetectionStrategy, ChangeDetectorRef } from "@angular/core";
import { BaseCriteriaTemplateComponent } from "../baseType.component";
import { ReportingService } from "../../../../../reporting.service";
import { Subscription } from "rxjs";
import { ICriteriaTemplate, TemplateType } from "../../models/criteriaTemplate.interface";
import { ICriteriaOutput } from "../../models/save/criteriaOutput.interface";
import { MultiselectOutput } from "../../models/save/criteriaOutput.model";

@Component({
    selector: 'type3',
    styleUrls: ['../../templateCriteria.component.scss', '../../../criteria.component.scss'],
    templateUrl: 'type3.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush,
    providers: [{ provide: BaseCriteriaTemplateComponent, useExisting: Type3Component }]
})
export class Type3Component extends BaseCriteriaTemplateComponent implements ICriteriaTemplate {
    private sub: Subscription;
    private loadSub: Subscription;
    public items: string[];
    public selected: string[] = [];

    public type: TemplateType = TemplateType.Multiselect;

    constructor(
        private toolsService: ReportingService,
        private cdRef: ChangeDetectorRef) {
        super(toolsService, cdRef);
    }

    @Input() level3: string;

    ngOnInit() {
        this.sub = this.toolsService.getCriteria(this.templateCriteria.id, 3, true).subscribe(data => {
            this.items = data.collectionItems;
            if (this.edit == 'true')
                this.loadMultiSelectData('typeThreeSelectedItems');
            else
                this.cdRef.markForCheck();
        });

        this.loadSub = this.load.subscribe(data => {
            this.selected = data || [];
            this.cdRef.markForCheck();
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
        this.loadSub.unsubscribe();
    }

    public select(item: any) {
        if (this.selected.indexOf(item) == -1)
        {
            this.selected.push(item);
            BaseCriteriaTemplateComponent.changed.emit(true);
        }
    }

    public unselect(index: number) {
        this.selected.splice(index, 1);
        BaseCriteriaTemplateComponent.changed.emit(this.selected.length > 0);
    }

    public onEnter(value: string) {
        this.sub = this.toolsService.getCriteriabyName(this.templateCriteria.id, 3, value).subscribe(data=>{
            this.items = data.collectionItems;            
            this.cdRef.markForCheck();
        });
    }

    public save(): ICriteriaOutput {
        return new MultiselectOutput(
            this.level3,
            this.templateCriteria.criteriaLevel2,
            this.templateCriteria.id,
            this.templateCriteria.name,
            this.selected);
    }
}